//
//  HMEmoticonTools.swift
//  Weibo
//
//  Created by Apple on 2017/7/17.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import YYModel

//  每页显示20个表情
let NumberOfPage = 20
//  最近表情的归档和解档的路径
private let RecentPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recentEmoticonArray.archive")
//  表情操作工具类
class HMEmoticonTools: NSObject {

    //  单例的全局访问点
    static let sharedTools: HMEmoticonTools = HMEmoticonTools()
    //  构造函数私有化
    private override init() {
        super.init()
    }
    //  创建表情bundle对象
    lazy var emoticonBundle: Bundle = {
        //  表情bundle路径
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)!
        //  根据路径创建bundle对象
        let bundle = Bundle(path: path)!
        return bundle
    }()
    
    //  最近表情
    fileprivate lazy var recentEmoticonArray: [HMEmoticon] = {
        //  本地沙盒有最近表情直接返回
        if let localArray = self.loadRecentEmoticonArray() {
            return localArray
        }
        let emoticonArray = [HMEmoticon]()
        return emoticonArray
    }()
    
    //  默认表情
    fileprivate lazy var defaultEmoticonArray: [HMEmoticon] = {
        return self.loadEmotionData(folderName: "default", fileName: "info.plist")
    }()
    //  emoji表情
    fileprivate lazy var emojiEmoticonArray: [HMEmoticon] = {
        return self.loadEmotionData(folderName: "emoji", fileName: "info.plist")
    }()
    //  浪小花
    fileprivate lazy var lxhEmoticonArray: [HMEmoticon] = {
        return self.loadEmotionData(folderName: "lxh", fileName: "info.plist")
    }()
    
    //  准备表情视图所需要的数据源
    lazy var allEmoticonArray: [[[HMEmoticon]]] = {
        
        return [
            [self.recentEmoticonArray],
            self.sectionWith(emoticonArray: self.defaultEmoticonArray),
            self.sectionWith(emoticonArray: self.emojiEmoticonArray),
            self.sectionWith(emoticonArray: self.lxhEmoticonArray)
        ]
    
    }()
    
    //  根据文件夹和文件名加载表情数据
    fileprivate func loadEmotionData(folderName: String, fileName: String) -> [HMEmoticon] {
        let path = self.emoticonBundle.path(forResource: folderName + "/" + fileName, ofType: nil)!
        //  加载plist数据
        let dicArray = NSArray(contentsOfFile: path) as! [[String: Any]]
        //  使用YYModel完成字典转模型
        let modelArray = NSArray.yy_modelArray(with: HMEmoticon.self, json: dicArray) as! [HMEmoticon]
        for model in modelArray {
            if model.type == "0" {
                //  拼接图片路径
                model.path = folderName + "/" + model.png!
            }
        }
        return modelArray
    }
    
    //  拆分每种表情对应的二维数组
    func sectionWith(emoticonArray: [HMEmoticon]) -> [[HMEmoticon]] {
        //  根据个数计算每种表情的页数
        let pageCount = (emoticonArray.count - 1) / NumberOfPage + 1
        var tempArray = [[HMEmoticon]]()
        //  遍历页数，截取每页对应的表情数据
        for pageIndex in 0..<pageCount {
            let loc = pageIndex * NumberOfPage
            var len = NumberOfPage
            if loc + len > emoticonArray.count {
                //  超出数组的范围，截取剩余个数
                len = emoticonArray.count - loc
            }
            //  截取范围
            let range = NSMakeRange(loc, len)
            let subArray = (emoticonArray as NSArray).subarray(with: range) as! [HMEmoticon]
            tempArray.append(subArray)
        }
        return tempArray
    }
    
    //  保存点击的表情模型到最近表情
    func saveRecentEmoticon(emoticon: HMEmoticon, finishCallBack: ()->()) {
        
        //  1.判断点击的表情是否在最近表情里面
        for (i, model) in recentEmoticonArray.enumerated() {
            if emoticon.type == "0" {
                //  图片表情
                if emoticon.chs == model.chs {
                    //  2.如果有删除最近数组里面的表情
                    recentEmoticonArray.remove(at: i)
                    break
                }
            } else {
                //  emoji表情
                if emoticon.code == model.code {
                    //  2.如果有删除最近数组里面的表情
                    recentEmoticonArray.remove(at: i)
                    break
                }
            }
        }
        
        //  3.把点击的表情插入到最近数组里面的第一个位置
        recentEmoticonArray.insert(emoticon, at: 0)
        //  4.如果最近数组里面的表情个数超过20个删除最后一个元素
        if recentEmoticonArray.count > 20 {
            recentEmoticonArray.removeLast()
        }
        //  5.更新数据
        allEmoticonArray[0][0] = recentEmoticonArray
        
        //  6.保存最近表情到沙盒
        NSKeyedArchiver.archiveRootObject(recentEmoticonArray, toFile: RecentPath)
        
        //  7.重新加载最近这组表情数据
        finishCallBack()
        
        
    }
    
    //  解档最近表情数据
    func loadRecentEmoticonArray() -> [HMEmoticon]? {
        let localEmoticonArray = NSKeyedUnarchiver.unarchiveObject(withFile: RecentPath) as? [HMEmoticon]
        return localEmoticonArray
    }
    
    //  根据表情描述查找表情模型
    func searchEmoticonWith(chs: String) -> HMEmoticon? {
        for model in defaultEmoticonArray {
            if model.chs == chs {
                return model
            }
        }
        
        for model in lxhEmoticonArray {
            if model.chs == chs {
                return model
            }
        }
        return nil
    }
    
}
